package com.javablog.controller;

import com.javablog.dto.TagDto;
import com.javablog.dto.response.MessageResponse;
import com.javablog.model.Tag;
import com.javablog.repository.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/tags")
public class TagController {
    
    @Autowired
    private TagRepository tagRepository;
    
    @GetMapping
    public ResponseEntity<?> getAllTags() {
        List<Tag> tags = tagRepository.findAll();
        List<TagDto> tagDtos = tags.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(tagDtos);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getTagById(@PathVariable Long id) {
        Tag tag = tagRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("错误：标签未找到。"));
        
        return ResponseEntity.ok(convertToDto(tag));
    }
    
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createTag(@Valid @RequestBody TagDto tagDto) {
        if (tagRepository.existsByName(tagDto.getName())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误：标签名称已存在!"));
        }
        
        Tag tag = new Tag();
        tag.setName(tagDto.getName());
        
        tagRepository.save(tag);
        
        return ResponseEntity.ok(new MessageResponse("标签创建成功!"));
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateTag(@PathVariable Long id, @Valid @RequestBody TagDto tagDto) {
        Tag tag = tagRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("错误：标签未找到。"));
        
        if (!tag.getName().equals(tagDto.getName()) && tagRepository.existsByName(tagDto.getName())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误：标签名称已存在!"));
        }
        
        tag.setName(tagDto.getName());
        
        tagRepository.save(tag);
        
        return ResponseEntity.ok(new MessageResponse("标签更新成功!"));
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteTag(@PathVariable Long id) {
        if (!tagRepository.existsById(id)) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误：标签未找到!"));
        }
        
        tagRepository.deleteById(id);
        
        return ResponseEntity.ok(new MessageResponse("标签删除成功!"));
    }
    
    private TagDto convertToDto(Tag tag) {
        TagDto tagDto = new TagDto();
        tagDto.setId(tag.getId());
        tagDto.setName(tag.getName());
        tagDto.setArticleCount(tag.getArticles().size());
        
        return tagDto;
    }
} 